package com.lemon.smartsafety.ui.fragment.address;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.address.AddrBookApplyVo;
import com.lemon.smartsafety.entity.address.AddrBookInviteVo;
import com.lemon.smartsafety.entity.common.IndexModel;
import com.lemon.smartsafety.entity.event.address.AddressRefreshEvent;
import com.lemon.smartsafety.entity.event.address.ApplyHandleEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.AddressBookServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.ui.adapter.address.AddressApplyAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.ui.widget.IndexView;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Cooliean on 16/4/11.
 */
public class AddressBookApplyFragment extends BaseFragment implements RecyclerTClickListener<IndexModel> {
    private LoggerHelper loggerHelper = new LoggerHelper(AddressBookApplyFragment.class);
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.tv_tip)
    TextView                  tvTipTop;
    @Bind(R.id.tv_center_tip)
    TextView                  tvCenterTip;
    @Bind(R.id.index_view)
    IndexView                 mIndexView;
    @Bind(R.id.float_button)
    FloatingActionButton      mFloatButton;
    @Bind(R.id.multiStateView)
    MultiStateView            mMultiStateView;


    private LinearLayoutManager mLayoutManager;
    public List<IndexModel> mDataList = new ArrayList<>();
    private AddressApplyAdapter mAdapter;


    public static AddressBookApplyFragment newInstance() {
        AddressBookApplyFragment fragment = new AddressBookApplyFragment();
        return fragment;
    }

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_address_content;
    }

    @Override
    protected void initViews() {
        mAdapter = new AddressApplyAdapter(mDataList, this);
        mMultiStateView.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                if (mPullToRefreshRecyclerView != null) {
                    mPullToRefreshRecyclerView.beginRefreshing();
                }
            }
        });


        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.setLayoutManager(mLayoutManager);

        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.beginRefreshing();
        setIndexViewValue();
    }

    private void setIndexViewValue() {
        mPullToRefreshRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    if (mAdapter != null && mAdapter.getData().size() != 0) {
                        int index = mLayoutManager.findFirstVisibleItemPosition() - mPullToRefreshRecyclerView.getHeaderViewCount();
                        if (index < 0) {
                            index = 0;
                        }
                        tvTipTop.setText(mAdapter.getData().get(index).getIndexCharI());
                    } else {
                        //tvTipTop.setText("A");
                    }
                } catch (Exception e) {

                }
            }
        });

        if (mAdapter != null && mAdapter.getData().size() != 0) {
            tvCenterTip.setText(mAdapter.getData().get(0).getIndexCharI());
        }

        mIndexView.setOnChangedListener(new IndexView.OnChangedListener() {
            @Override
            public void onChanged(String text) {
                int position = mAdapter.getPositionForSection(text.charAt(0));
                if (position != -1) {
                    // position的item滑动到RecyclerView的可见区域，如果已经可见则不会滑动
                    mLayoutManager.scrollToPosition(position);
                }
            }
        });
        mIndexView.setTipTv(tvCenterTip);
    }

    private String getHttpTag() {
        return EventTag.TAG_ADDRESS_BOOK_MY_APPLY_LIST;
    }


    private void getNetData() {
        AddressBookServices.init().getApplyList();
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (getHttpTag().equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                //mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    httpRefresh((List<AddrBookInviteVo>) event.getObj());
                } else {
                    httpRefreshError(event.getMsg());
                }
            }
        } else if (EventTag.TAG_ADDRESS_BOOK_APPLY_HANDLE.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            mPullToRefreshRecyclerView.beginRefreshing();
                            AddressRefreshEvent refreshEvent = new AddressRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    public void httpRefresh(List<AddrBookInviteVo> data) {
        loggerHelper.json(data);
        mHUDUtil.hidden();
        if (data != null && !data.isEmpty()) {
            data = AddressBookServices.sortData(data);
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mDataList.clear();
            mDataList.addAll(data);
            mAdapter.notifyDataSetChanged();
        } else {
            mMultiStateView.setEmptyTip("您没有收到任何申请");
        }
    }

    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }



    @Subscribe
    public void onEventMainThread(final ApplyHandleEvent event) {
        if (ApplyHandleEvent.class.getName().equals(event.getTag())) {
            String title = "是否同意加入？";
            if (event.getType() == 0) {
                title = "是否拒绝加入？";
            }
            new MaterialDialog.Builder(getActivity()).content(title).positiveText("确定").negativeText("取消")
                                                     .onAny(new MaterialDialog.SingleButtonCallback() {
                                                         @Override
                                                         public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                             if (which == DialogAction.POSITIVE) {
                                                                 handleApply(event.getData(), event.getType());
                                                             }
                                                         }
                                                     }).show();
        }
    }

    private void handleApply(IndexModel model,int type) {
        AddrBookApplyVo vo = (AddrBookApplyVo) model;
        String repString = "1";
        if (type == 0) {
            repString = "2";
        }
        AddressBookServices.init().handleApply(vo.getBook_id() + "", vo.getCreate_user_id() + "", repString);
    }





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpUtils.getInstance().cancelTag(getHttpTag());
        ButterKnife.unbind(this);
    }

    @Override
    public void onItemClick(IndexModel data, int position) {

    }
}
